package com.eims.sls_app.ui;


import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

import org.json.JSONException;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.MySingleton;
import com.android.volley.toolbox.StringRequest;

import com.contans.view.TextVo;
import com.eims.sls_app.dataaccess.utils.HttpUtils;
import com.eims.sls_app.protocol.MD5;
import com.eims.sls_app.protocol.RspBodyBaseBean;
import com.eims.sls_app.utils.App;
import com.eims.sls_app.utils.BaseHelper;
import com.eims.sls_app.utils.MyAsynTaskWithProgress;
import com.eims.sls_app.utils.RequestUtil;
import com.eims.sls_app.view.MyToast;
import com.google.gson.Gson;
import com.saoma.weixin.until.TLinx2Util;
import com.saoma.weixin.until.TLinxAESCoder;
import com.saoma.weixin.until.TestParams;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;

import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;
import bls.juejin.cn.R;
import net.sf.json.JSONObject;

public class AmountOfChargeToweiWX extends MyBaseActivity implements OnClickListener {
	public final static String TAG = "AmountOfCharge";
	public String feeName = "好球充值";
	public String feePrice = "";
	public String feeDesc = "好球充值";
	public String Key = "4297f44b13955235245b2497399d7a93";
	// public String Key_kefu = "4297f44b13955235245b2497399d7a93";
	public ImageButton btn_back;
	public EditText recahge_et_money;
	// 立即充值
	public Button recharge_btn_ok;
	public TextView recharge_tv_tishi;
	public static Context mContext;
	// 充值类型1,银联2,支付宝3,微信4.支付宝快捷支付
	public int type;
	// Request
	private Request jsonObjectRequest;
	private String RE = "tb_Regesitor";
	private String DOWN = "tb_DownLoadKey";
	// 充值金额
	private double dMoney;
	// 最小充值金额
	private double Min;
	// 订单号
	public String outer_no;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_amount_of_charge);
		mContext = AmountOfChargeToweiWX.this;
		
		InitView();
		Bundle bundle = getIntent().getExtras();
		type = bundle.getInt("Type");
		if (type == 4) {
			recharge_tv_tishi.setText("温馨提示：充值免手续费，充值金额需100%消费，奖金提款不受限制" + "\n" + "如未打开支付宝app,请结束支付宝进程再试一次。");
		}

	}

	private void InitView() {
		// TODO Auto-generated method stub
		btn_back = (ImageButton) findViewById(R.id.btn_back);
		btn_back.setOnClickListener(this);
		recahge_et_money = (EditText) findViewById(R.id.recahge_et_money);
		recharge_btn_ok = (Button) findViewById(R.id.recharge_btn_ok);
		recharge_tv_tishi = (TextView) findViewById(R.id.recharge_tv_tishi);
		recharge_btn_ok.setOnClickListener(this);
	}

	@Override
	public void onClick(View v) {
		// TODO Auto-generated method stub
		switch (v.getId()) {
		case R.id.btn_back:
			AmountOfChargeToweiWX.this.finish();
			break;
		case R.id.recharge_btn_ok:

			// 获取金额
			// if(ClickFilter.filter()) return;
			feePrice = recahge_et_money.getText().toString();

			if (feePrice.length() > 0 && !feePrice.equals("")) {
				int parseInt = Integer.parseInt(feePrice);
				if (parseInt >= 20) {

					// 获取订单号
					MySingleton mySingleton = MySingleton.getInstance(AmountOfChargeToweiWX.this);
					if (type == 4) {
						jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no_kefu,
								new Response.Listener<String>() {
									@Override
									public void onResponse(String tn) {
										try {
											outer_no = tn;
											if (!outer_no.equals("") && outer_no.length() > 0) {
												Log.i(TAG,
														"获取金额" + App.user.getUid() + "|" + outer_no + "|" + "支付宝");
											

											} else {
												MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败亲重新操作!").show();
											}
										} catch (Exception e) {
											e.printStackTrace();
											if (RequestUtil.DEBUG) {

											}
											MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
										}
									}
								}, new Response.ErrorListener() {

									@Override
									public void onErrorResponse(VolleyError error) {

										if (RequestUtil.DEBUG) {
											String className = error.getClass().getName();
											Log.i(TAG, "获取订单出错---" + error.getMessage());
										}
										MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
									}
								}) {
							@Override
							protected Map<String, String> getParams() throws AuthFailureError {
								/*
								 * String[] names = { "userID", "money" ,"type"}; String values[] = {
								 * App.user.getUid(), feePrice ,type+""};
								 */
								String[] names = { "userID", "money" };
								String values[] = { App.user.getUid(), feePrice };
								if (RequestUtil.DEBUG)
									;
								Map<String, String> params = new HashMap<String, String>();
								for (int i = 0; i < names.length; i++) {
									params.put(names[i], values[i]);
								}
								return params;
							}
						};

					} else if (type == 11) {
						jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_saoma_shenzhen,
								new Response.Listener<String>() {
									@Override
									public void onResponse(String tn) {
										try {
											outer_no = tn;
											if (!outer_no.equals("") && outer_no.length() > 0) {
												Log.i(TAG,
														"获取金额" + App.user.getUid() + "|" + outer_no + "|" + "微信");
											
												MyAsynTask asynTask1=new MyAsynTask();
												asynTask1.execute();
												

											} else {
												MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败亲重新操作!").show();
											}
										} catch (Exception e) {
											e.printStackTrace();
											if (RequestUtil.DEBUG) {

											}
											MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
										}
									}
								}, new Response.ErrorListener() {

									@Override
									public void onErrorResponse(VolleyError error) {

										if (RequestUtil.DEBUG) {
											String className = error.getClass().getName();
											Log.i(TAG, "获取订单出错---" + error.getMessage());
										}
										MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
									}
								}) {
							@Override
							protected Map<String, String> getParams() throws AuthFailureError {
								/*
								 * String[] names = { "userID", "money" ,"type"}; String values[] = {
								 * App.user.getUid(), feePrice ,type+""};
								 */
								String[] names = { "userID", "money" };
								String values[] = { App.user.getUid(), feePrice };
								if (RequestUtil.DEBUG)
									;
								Map<String, String> params = new HashMap<String, String>();
								for (int i = 0; i < names.length; i++) {
									params.put(names[i], values[i]);
								}
								return params;
							}
						};
					}else {
						jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no,
								new Response.Listener<String>() {
									@Override
									public void onResponse(String tn) {
										try {
											outer_no = tn;
											if (!outer_no.equals("") && outer_no.length() > 0) {

											

											} else {
												MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败亲重新操作!").show();
											}
										} catch (Exception e) {
											e.printStackTrace();
											if (RequestUtil.DEBUG) {

											}
											MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
										}
									}
								}, new Response.ErrorListener() {

									@Override
									public void onErrorResponse(VolleyError error) {

										if (RequestUtil.DEBUG) {
											String className = error.getClass().getName();
											Log.i(TAG, "获取订单出错---" + error.getMessage());
										}
										MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
									}
								}) {
							@Override
							protected Map<String, String> getParams() throws AuthFailureError {

								String[] names = { "userID", "money" };
								String values[] = { App.user.getUid(), feePrice };
								if (RequestUtil.DEBUG)
									;
								Map<String, String> params = new HashMap<String, String>();
								for (int i = 0; i < names.length; i++) {
									params.put(names[i], values[i]);
								}
								return params;
							}
						};

					}

					jsonObjectRequest.setShouldCache(false);// 是否设置缓存
					mySingleton.addToRequestQueue(jsonObjectRequest);
				} else {
					MyToast.getToast(AmountOfChargeToweiWX.this, "充值金额小于20元!").show();
				}
			} else {
				Log.i(TAG, "获取金额" + recahge_et_money.getHint().toString());
				// MyToast.getToast(AmountOfCharge.this, "请输入充值金额!").show();
				getPay();
			}

			// if(ClickFilter.filter()) return;
			break;

		default:
			break;
		}
	}

	
	private void getPay() {

		MySingleton mySingleton = MySingleton.getInstance(AmountOfChargeToweiWX.this);
		if (type == 4) {
			jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no_kefu,
					new Response.Listener<String>() {
						@Override
						public void onResponse(String tn) {
							try {
								outer_no = tn;
								if (!outer_no.equals("") && outer_no.length() > 0) {

								

								} else {
									MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败亲重新操作!").show();
								}
							} catch (Exception e) {
								e.printStackTrace();
								if (RequestUtil.DEBUG) {

								}
								MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {

							if (RequestUtil.DEBUG) {
								String className = error.getClass().getName();
								Log.i(TAG, "获取订单出错---" + error.getMessage());
							}
							MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
						}
					}) {
				@Override
				protected Map<String, String> getParams() throws AuthFailureError {

					String[] names = { "userID", "money" };
					String values[] = { App.user.getUid(), "100" };
					if (RequestUtil.DEBUG)
						;
					Map<String, String> params = new HashMap<String, String>();
					for (int i = 0; i < names.length; i++) {
						params.put(names[i], values[i]);
					}
					return params;
				}
			};

		} else if (type == 11) {
			jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_saoma_shenzhen,
					new Response.Listener<String>() {
						@Override
						public void onResponse(String tn) {
							try {
								outer_no = tn;
								if (!outer_no.equals("") && outer_no.length() > 0) {

								

								} else {
									MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败亲重新操作!").show();
								}
							} catch (Exception e) {
								e.printStackTrace();
								if (RequestUtil.DEBUG) {

								}
								MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {

							if (RequestUtil.DEBUG) {
								String className = error.getClass().getName();
								Log.i(TAG, "获取订单出错---" + error.getMessage());
							}
							MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
						}
					}) {
				@Override
				protected Map<String, String> getParams() throws AuthFailureError {

					String[] names = { "userID", "money" };
					String values[] = { App.user.getUid(), "100" };
					if (RequestUtil.DEBUG)
						;
					Map<String, String> params = new HashMap<String, String>();
					for (int i = 0; i < names.length; i++) {
						params.put(names[i], values[i]);
					}
					return params;
				}
			};
		}  else {
			jsonObjectRequest = new StringRequest(Request.Method.POST, App.pay_outer_no,
					new Response.Listener<String>() {
						@Override
						public void onResponse(String tn) {
							try {
								outer_no = tn;
								if (!outer_no.equals("") && outer_no.length() > 0) {

								

								} else {
									MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败亲重新操作!").show();
								}
							} catch (Exception e) {
								e.printStackTrace();
								if (RequestUtil.DEBUG) {

								}
								MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
							}
						}
					}, new Response.ErrorListener() {

						@Override
						public void onErrorResponse(VolleyError error) {

							if (RequestUtil.DEBUG) {
								String className = error.getClass().getName();
								Log.i(TAG, "获取订单出错---" + error.getMessage());
							}
							MyToast.getToast(AmountOfChargeToweiWX.this, "获取订单失败").show();
						}
					}) {
				@Override
				protected Map<String, String> getParams() throws AuthFailureError {

					String[] names = { "userID", "money" };
					String values[] = { App.user.getUid(), "100" };
					if (RequestUtil.DEBUG)
						;
					Map<String, String> params = new HashMap<String, String>();
					for (int i = 0; i < names.length; i++) {
						params.put(names[i], values[i]);
					}
					return params;
				}
			};

		}
		jsonObjectRequest.setShouldCache(false);// 是否设置缓存
		mySingleton.addToRequestQueue(jsonObjectRequest);
	}

	public void getSenzhenXplay(String name, String price, String desc, String outer_no) {

	}
	
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		
		finish();
	}


	class MyAsynTask extends AsyncTask<Integer, Integer, String> {
		
		String error = "-1";

		@Override
		protected String doInBackground(Integer... params) {
			
			queryOrder("81685228", "Weixin", null, "现金支付测试1",Integer.parseInt(feePrice)*100,
	                null, null, Integer.parseInt(feePrice)*100,null, null, null, null,
	                null, null, null, "http://local.ttg.cn:8400/tlinx2apidemo1/callback/scanpay_cashier/payResult");
			
	return 0+"";
		}

		@Override
		protected void onPostExecute(String result) {
			super.onPostExecute(result);
			
		}
	}
	
	/*
	 * 微信扫码
	 */
	
	/**
     * Method queryOrderList
     * Description 说明：
     *
     * @param outNo 说明：
     * @param pmtTag 说明：
     * @param pmtName 说明：
     * @param ordName 说明：
     * @param originalAmount 说明：
     * @param discountAmount 说明：
     * @param ignoreAmount 说明：
     * @param tradeAmount 说明：
     * @param tradeAccount 说明：
     * @param tradeNo 说明：
     * @param tradeResult 说明：
     * @param remark 说明：
     * @param authCode 说明：
     * @param tag 说明：
     * @param jumpUrl 说明：
     * @param notifyUrl 说明：
     */
    public void queryOrder(String outNo, String pmtTag, String pmtName, String ordName, Integer originalAmount,
                               Integer discountAmount, Integer ignoreAmount, Integer tradeAmount, String tradeAccount,
                               String tradeNo, String tradeResult, String remark, String authCode, String tag,
                               String jumpUrl, String notifyUrl) {

        // 初始化参数
        String timestamp = new Date().getTime() / 1000 + "";    // 时间

        try {

            // 固定参数
            TreeMap<String, String> postmap = new TreeMap<String, String>();    // 请求参数的map

            postmap.put("open_id", TestParams.OPEN_ID);
            postmap.put("timestamp", timestamp);

            TreeMap<String, String> datamap = new TreeMap<String, String>();    // data参数的map

            datamap.put("out_no", outNo);
            datamap.put("pmt_tag", pmtTag);
            datamap.put("pmt_name", pmtName);
            datamap.put("ord_name", ordName);
            datamap.put("original_amount", originalAmount+"");
            datamap.put("discount_amount", discountAmount+"");
            datamap.put("ignore_amount", ignoreAmount+"");
            datamap.put("trade_amount", tradeAmount+"");
            datamap.put("trade_account", tradeAccount);
            datamap.put("trade_no", tradeNo);
            datamap.put("trade_result", tradeResult);
            datamap.put("remark", remark);
            datamap.put("auth_code", authCode);
            datamap.put("tag", tag);
            datamap.put("jump_url", jumpUrl);
            datamap.put("notify_url", notifyUrl);

            /**
             * 1 data字段内容进行AES加密，再二进制转十六进制(bin2hex)
             */
            TLinx2Util.handleEncrypt(datamap, postmap);

            /**
             * 2 请求参数签名 按A~z排序，串联成字符串，先进行sha1加密(小写)，再进行md5加密(小写)，得到签名
             */
            TLinx2Util.handleSign(postmap);

            /**
             * 3 请求、响应
             */
            String rspStr = TLinx2Util.handlePost(postmap, TestParams.PAYORDER);
            System.out.println("====post响应字符串= " + rspStr);

            /**
             * 4 验签  有data节点时才验签
             */
            JSONObject respObject = JSONObject.fromObject(rspStr);
            Object dataStr    = respObject.get("data");

            if (!rspStr.isEmpty() && ( dataStr != null )) {
                if (TLinx2Util.verifySign(respObject)) {    // 验签成功

                    /**
                     * 5 AES解密，并hex2bin
                     */
                    String respData = TLinxAESCoder.decrypt(dataStr.toString(), TestParams.OPEN_KEY);

                    System.out.println("=================响应data内容= " + respData);
                    JSONObject jsonObject = JSONObject.fromObject(respData);
                    Object tradeQrcode = jsonObject.get("trade_qrcode");
                    System.out.println("=================支付二维码地址= " + tradeQrcode.toString());
                    System.out.println("=================trade_result= " + jsonObject.get("trade_result").toString());
                    String s1 = jsonObject.get("trade_result").toString();
                    System.out.println("=================return_code= " + JSONObject.fromObject(s1.substring(1,s1.length()-1)).get("return_code"));

                } else {
                    System.out.println("==========验签失败==========");
                }
            } else {
                System.out.println("==========没有返回data数据==========");
            }
            System.out.println("==========没有返回data数据44==========");  
        } catch (Exception e) {
            e.printStackTrace();
            System.out.println("==========没有返回data数据44=========="+e);  
            
        }
    }
	
}
